package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:手写阻塞队列
 * User: 王圆豪
 * Date: 2025-04-30
 * Time: 23:33
 */

class MyBlockingQueue{
    //利用数组实现队列
    private String[] data = null;
    //首元素位置
    private int head = 0;
    //尾元素位置
    private int tail = 0;
    //元素个数
    private int size = 0;

    //构造方法（有参数）
    public MyBlockingQueue(int cap){
        data = new String[cap];
    }

    //入队列
    public synchronized void put(String s) throws InterruptedException {
        while (size >= data.length) {
            this.wait();
//            return;
        }
        if(tail >= data.length){
            tail = 0;
        }
        data[tail] = s;
        this.notify();
        tail++;
    }

    //出队列
    public synchronized String take() throws InterruptedException {
        while (size == 0){
            this.wait();
//            return null;
        }
        String tmp = data[head];
        head++;
        if (head >= data.length){
            head = 0;
        }
        size--;
        this.notify();
        return tmp;
    }
}
public class Demo26 {
    public static void main(String[] args) {
    }
}
